﻿namespace RialternativeSample.ViewModels
{
    using System.Collections.ObjectModel;
    using System.Windows.Input;
    using RialternativeSample.Client.Commanding;
    using RialternativeSample.Client.Infrastructure;
    using RialternativeSample.Client.Northwind.Interfaces;
    using RialternativeSample.Server.NorthwindService;
    using RialternativeSample.ViewModels.Interfaces;

    public class CustomersViewModel : Notifier, ICustomersViewModel
    {
        private ObservableCollection<Customers> customers;

        private ICustomersDataService customersDataService;

        public CustomersViewModel(ICustomersDataService customersDataService)
        {
            this.customersDataService = customersDataService;

            this.DeleteCustomerCommand = new RelayCommand<Customers>(this.DeleteCustomer, c => customersDataService.CanDeleteCustomers);
            this.EndCustomerEditCommand = new RelayCommand<Customers>(this.EndCustomerEdit, c => this.CanEditCustomers);

            customersDataService.GetCustomersAsync(customers => this.Customers = customers);
        }

        public ICommand DeleteCustomerCommand { get; private set; }

        public ICommand EndCustomerEditCommand { get; private set; }

        public bool CanEditCustomers
        {
            get
            {
                return this.customersDataService.CanEditCustomers;
            }
        }

        public ObservableCollection<Customers> Customers
        {
            get
            {
                return this.customers;
            }

            private set
            {
                this.customers = value;
                this.RaisePropertyChanged(() => this.Customers);
            }
        }

        private void DeleteCustomer(Customers customer)
        {
            this.customersDataService.DeleteCustomer(customer);
            this.customersDataService.PersistChangesAsync(null);
        }

        private void EndCustomerEdit(Customers customer)
        {
            if (customer.HasChanges)
            {
                this.customersDataService.PersistChangesAsync(null);
            }
        }
    }
}
